
package sale

import (
	"strings"
	"errors"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

// 销售标签
type SaleTag struct {
    Id           int64   `orm:"column(id);pk;auto" json:"id" form:"id"`                         /* 编号 */
	PartnerId    int64   `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`   /* 商户编号 */
	TagCode      string  `orm:"column(tag_code)" json:"tag_code" form:"tag_code"`               /* 标签代码 */
	TagName      string  `orm:"column(tag_name);null" json:"tag_name"`                          /* 标签名*/
	GoodsImage   string  `orm:"column(goods_image);null" json:"goods_image" form:"goods_image"` /* 商品的遮盖图 */
	IsInternal   int32   `orm:"column(is_internal)" json:"is_internal" form:"is_internal"`      /* 是否内部 */
	Enabled      int32   `orm:"column(enabled)" json:"enabled" form:"enabled"`                  /* 是否启用 */
}

func init() {
    orm.RegisterModel(new(SaleTag))   
}

// 初始化销售标签
func  InitDefaultSaleTags(partnerId int64) error {
	/*
	if len(this.GetAllSaleTags()) != 0 {
		return errors.New("已经存在数据，无法初始化!")
	}*/
	arr := []SaleTag{
		SaleTag{
			TagName: "新品上架",
			TagCode: "new-goods",
		},
		SaleTag{
			TagName: "热销商品",
			TagCode: "hot-sales",
		},
		SaleTag{
			TagName: "特色商品",
			TagCode: "special-goods",
		},
		SaleTag{
			TagName: "优惠促销",
			TagCode: "prom-sales",
		},
		SaleTag{
			TagName: "尾品清仓",
			TagCode: "clean-goods",
		},
	}
	var err error
	for _, v := range arr {
		v.Enabled = 1
		v.PartnerId = partnerId
		v.IsInternal = 1
		_, err = AddSaleTag(&v)
	}
	return err
}

func AddSaleTag(m *SaleTag) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetSaleTagById(id int64) (v *SaleTag, err error) {
	o := models.GetDefaultDB()
	v = &SaleTag{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllSaleTags(start,end string,query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*SaleTag,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(SaleTag))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*SaleTag
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	   
		return lists, cnt, nil
	}
	return nil, 0, err
}
	
func UpdateSaleTagById(m *SaleTag, param ...string) (err error) {
	o := models.GetDefaultDB()
	v := SaleTag{Id: m.Id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Update(m, param...); err == nil {
			return nil
		}
	}
	return
}

func DeleteSaleTag(id int64) (err error) {
	o := models.GetDefaultDB()
	v := SaleTag{Id: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

// 获取商品
/*
func  GetPagedValueGoodsBySaleTag(partnerId, tagId, begin, end int) (int, []*Goods) {
	var total int
	arr := []*Goods{}
	this.Connector.ExecScalar(fmt.Sprintf(`SELECT COUNT(0) FROM gs_goods INNER JOIN gs_item ON gs_item.id = gs_goods.item_id
		 WHERE gs_item.state=1  AND gs_item.on_shelves=1 AND gs_item.id IN (
			SELECT g.item_id FROM gs_item_tag g INNER JOIN gs_sale_tag t ON t.id = g.sale_tag_id
			WHERE t.partner_id=? AND t.id=?)`), &total, partnerId, tagId)
	if total > 0 {
		this.Connector.GetOrm().SelectByQuery(&arr, `SELECT * FROM gs_goods INNER JOIN gs_item ON gs_item.id = gs_goods.item_id
		 WHERE gs_item.state=1  AND gs_item.on_shelves=1 AND gs_item.id IN (
			SELECT g.item_id FROM gs_item_tag g INNER JOIN gs_sale_tag t ON t.id = g.sale_tag_id
			WHERE t.partner_id=? AND t.id=?) LIMIT ?,?`, partnerId, tagId, begin, end)
	}
	return total, arr
}
*/

// 获取商品的销售标签
func  GetItemSaleTags(itemId int) []*SaleTag {
	arr := []*SaleTag{}
	sql := "SELECT * FROM gs_sale_tag WHERE id IN (SELECT sale_tag_id FROM gs_item_tag WHERE item_id=?) AND enabled=1"
	o := models.GetDefaultDB()
	o.Raw(sql, itemId).QueryRows(&arr)
	return arr
}

// 清理商品的销售标签
func  CleanItemSaleTags(itemId int) error {
    o := models.GetDefaultDB()
	_, err := o.Raw("delete from `gs_item_tag` where item_id = ?", itemId).Exec()
	return err
}

// 保存商品的销售标签
func  SaveItemSaleTags(itemId int, tagIds []int) error {
	var err error
	o := models.GetDefaultDB()
	if tagIds == nil {
		return errors.New("SaleTag Ids can't be null.")
	}
	for _, v := range tagIds {
		_, err = o.Raw("insert into gs_item_tag(item_id,sale_tag_id) values(?,?)", itemId, v).Exec()
	}
	return err
}


